package cn.alcatraz.org.service.impl;

import cn.alcatraz.basic.service.impl.BaseServiceImpl;
import cn.alcatraz.org.domain.Employee;
import cn.alcatraz.org.mapper.EmployeeMapper;
import cn.alcatraz.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
    * @Title: save
    * @Description: 添加一条员工数据
    * @Author: TinyYu
    * @Version: 1.0
    * @Date:  2022/6/21 17:13  
    * @Parameters: 
    * @Return 
    */
    @Override
    @Transactional
    public void save(Employee employee) {
        // 密码加密
        // 获取盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        employee.setSalt(salt);
        // 加盐
        String newPassword = (salt + "12345678" + salt);
        // 加密
        employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()).toUpperCase());

        employeeMapper.save(employee);
    }

    /**
    * @Title: updateById
    * @Description: 通过id修改员工数据
    * @Author: TinyYu
    * @Version: 1.0
    * @Date:  2022/6/21 17:14  
    * @Parameters: 
    * @Return 
    */
    @Override
    @Transactional
    public void updateById(Employee employee) {
        // 是否修改密码
        if (employee.getPassword() != null) {
            // 获取盐值
            String salt = UUID.randomUUID().toString().toUpperCase();
            employee.setSalt(salt);
            // 加盐
            String newPassword = (salt + employee.getPassword() + salt);
            // 加密
            employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()).toUpperCase());
        } else {
            Employee oldEmployee = employeeMapper.loadById(employee.getId());
            employee.setSalt(oldEmployee.getSalt());
            employee.setPassword(oldEmployee.getPassword());
        }
        employeeMapper.updateById(employee);
    }
}
